# -*- coding: UTF-8 -*-
"""
Course:        CS408 Computer Science Project B, TEAM 1
Semester:      2010 SPRING
Project:       DOHN(Web-based Account Book System)

File:          utils.py
Description:   Utility package
Class:         None

Author:        SungHyuk Im
"""


import os
import datetime
import time
import mod_python
import re

import db


def get_abs_path():
    """
    @author: SungHyuk Im
    @summary: Absolute path.
    @return: Apache server path for this system
    
    @attention: return string doesn't end with '/'.
    """
    # v1
    #proj_path = "C:/APM/htdocs/test"
    # v2
    #: dohn. txt specifies the absolute path of current apache folder.
    #  ex) C:/APM/htdocs/test
    fptr = file("C:/dohn.txt", "r")
    proj_path = fptr.readline()
    fptr.close()
    return proj_path

def get_file_content(file_path):
    """
    @author: SungHyuk Im
    @summary: File content extractor.
    @return: Content of the file in the given path
    """
    file_path = os.path.normpath(file_path)
    if not os.path.isfile(file_path) :
        return False
    
    src = ""
    src_file = open(file_path, "r")
    for line in src_file:
        src += line
    src_file.close()
    return src

def get_current_time():
    """
    @author: SungHyuk Im
    @return: string, "YY-MM-DD HH-MM-SS"
    """
    now = time.localtime()
    astr = "%04d-%02d-%02d %02d:%02d:%02d" % \
    (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
    return astr

def get_current_date():
    """
    @author: SungHyuk Im
    
    @see: currentDate -> get_current_date
    """
    # v1: using datetime
#    now_all = datetime.datetime.now()
    #: 2010-04-22 01:07:32.051000
    
    # v2: using time
    now = time.localtime()
#    astr = "%04d-%02d-%02d" % \
#    (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
    #: 2010-04-22 01:08:58
    
    astr = "%04d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
    #: 2010-04-22
    return astr

def get_past_date():
    """
    @author: Sangyong Gil
    @summary: return date a week ago
    """
    # v1: using datetime
#    now_all = datetime.datetime.now()
    #: 2010-04-22 01:07:32.051000
    
    # v2: using time
    now = time.localtime()
#    astr = "%04d-%02d-%02d" % \
#    (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
    #: 2010-04-22 01:08:58
    month_date = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if now.tm_year%4==0 and now.tm_year%100 !=0 or now.tm_year%400==0:
        month_date[1]=29;
    else:
        month_date[1]=28;
    
    if now.tm_mday-6 < 1 and now.tm_mon == 1:
        day = month_date[11]+(now.tm_mday-6)
        month = 12
        year = now.tm_year-1    
    elif now.tm_mday-6 < 1 and now.tm_mon != 1:
        day = month_date[now.tm_mon-2]+(now.tm_mday-6)
        month = now.tm_mon-1
        year = now.tm_year
    else:
        day = now.tm_mday-6 
        month = now.tm_mon
        year = now.tm_year
    
    astr = "%04d-%02d-%02d" % (year, month, day)
    #: 2010-04-22
    return astr

def get_current_month():
    """
    @author: Sangyong Gil
    """
    # v1: using datetime
#    now_all = datetime.datetime.now()
    #: 2010-04-22 01:07:32.051000
    
    # v2: using time
    now = time.localtime()
#    astr = "%04d-%02d-%02d" % \
#    (now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
    #: 2010-04-22 01:08:58
    
    astr = "%04d-%d" % (now.tm_year, now.tm_mon)
    #: 2010-04-22
    return astr

def get_current_year():
    """
    @author: SungHyuk Im
    """
    return time.localtime().tm_year

def get_category_name(cat_num):
    """
    @author: SungHyuk Im
    @summary: Return category name whose index number is given parameter.  
    """
    query = "SELECT description FROM category_tb WHERE(num = '%s')" % (cat_num)
    data = db.run_query(query)
    if 0 == len(data):
        return 'undefined'
    else:
        return data[0][0]

def get_category_num(user_id, cat_name):
    """
    @author: SungHyuk Im
    @summary: Return category index whose name is given parameter.
    """
    query = "SELECT num FROM category_tb " + \
    "WHERE( description = '%s' AND user_id = '%s')" % (cat_name, user_id)
    data = db.run_query(query)
    if 0 == len(data):
        return False
    else:
        return data[0][0]
    
def get_category_dropdown_src(user_id):
    """
    @author: SungHyuk Im
    @summary: Return source of category dropdown box
    """
    # Fetch category_tb ----------------------------------------
    query = "SELECT num, description FROM category_tb " + \
            "WHERE(user_id = '%s') ORDER BY `order`" % (user_id)
    data = db.run_query(query)
    
    # Category ----------------------------------------
    in_src = []
    for atuple in data:
        num, desc = atuple
        astr = "\t<option value=%d>%s</option>\n" % (num, desc)
        in_src.append(astr)
    in_src = ''.join(in_src)
    if 1 >= len(in_src):
        in_src = str(in_src)
    return in_src

def get_category_dropdown_src_with_selected(user_id, category):
    """
    @author: Kyeonghwan Jin
    @change: num and category is converted into int to compare properly(by SungHyuk Im).
    """
    # Fetch category_tb ----------------------------------------
    query = "SELECT num, description FROM category_tb " + \
            "WHERE(user_id = '%s') ORDER BY `order`" % (user_id)
    data = db.run_query(query)
    
    # Category ----------------------------------------
    in_src = []
    for atuple in data:
        num, desc = atuple
        if(int(num) == int(category)):
            astr = "<option selected value=%d>%s</option>\n" % (num, desc)
        else :
            astr = "<option value=%d>%s</option>\n" % (num, desc)
        in_src.append(astr)
    in_src = ''.join(in_src)
    if 1 >= len(in_src):
        in_src = str(in_src)
    return in_src

def get_all_pattern_data(user_id):
    """
    @author: SungHyuk Im
    """
    # num  user_id  category  description 
    query = "SELECT num, category, description FROM pattern_tb WHERE" + \
            "(user_id = '%s')" % (user_id)
    data = db.run_query(query)
    return data

def get_all_transaction_data(user_id):
    """
    @author: SungHyuk Im
    """
    # num  user_id  date  description  amount  category  deleted 
    query = "SELECT num, date, description, amount, category, deleted " + \
            "FROM transaction_tb WHERE(user_id = '%s' AND deleted='0') ORDER BY `num`" % (user_id)
    data = db.run_query(query)
    return data

def get_url(req, adding):
    """
    @author: SungHyuk Im
    @summary: make URL as form of dohn.py/[adding]
    """
    # ex) req.uri: /test/dohn.py/sign_in
    
    #str_list = string.split(req.uri,"/")
    str_list = str(req.uri).split("/")
    #: ['', 'test', 'dohn.py', 'sign_in']
    
    items = [alist for alist in str_list if len(alist) > 0]
    #: ['test', 'dohn.py', 'sign_in']
    
    made = ""
    for aitem in items:
        made += "/" + aitem
        if aitem == "dohn.py":
            made += "/" + adding
            break
    #: /test/dohn.py/index
    
    return made

def get_main_with_msg(arg = ""):
    """
    @author: SungHyuk Im
    @deprecated: No longer used. Replaced by get_html_with_msg.
    """
    src_path = get_abs_path() + "/html/main_signup.html"
    src2 = get_file_content(src_path)   
    
    msg = \
    """
<script type="text/javascript">
    alert('<!---HERE!--->');
</script>
    """    
    #msg = string.replace(msg, "<!---HERE!--->", arg)
    msg = str(msg).replace("<!---HERE!--->", arg)
    
    src_path = get_abs_path() + "/html/main.html"
#    src = "Content-Type: text/html\n\n"
    src = get_file_content(src_path)
    #src = string.replace(src, "<!---HERE!--->", msg)
    src = str(src).replace("<!---HERE!--->", msg)
    return src

def get_html_with_msg(htmlfile, msg = ""):
    """
    @author: SungHyuk Im
    @summary: It returns HTML source whose name is htmlfile with alert msg.
        If msg is empty, just return source.
    @param htmlfile: html file name
    @param msg: message which we want to show when the page is loaded
    @return: HTML source
    """
    
    # Get html source
    # (It's no matter what filename or filename.html)
    htmlfile = str(htmlfile).split(".")
    htmlfile = str(htmlfile[0])
    src_path = get_abs_path() + "/html/" + htmlfile + ".html"
    src = get_file_content(src_path)
    
    # Replace with message
    if len(msg) == 0:
        return src
    msg = "<script type=\"text/javascript\">alert('%s');</script>" % ( msg )
    
    #src = string.replace(src, "<!---MSG!--->", msg)
    #result = re.sub("<!---MSG!--->", msg, src)
    result = str(src).replace("<!---MSG!--->", msg)
    return result

def get_split_float(s, tSep=',', dSep='.'):
    """
    @author: SungHyuk Im
    @summary: Number formatter with comma.
    
    @reference: http://is.gd/bRl14
    """
    if s == None:
        return 0
    #if isinstance(s, int) or isinstance(s,long) or isinstance(s,float):
    if not isinstance(s, str):
        s = str(s)
    if s[0] == '-' or s[0] == '+':
        lhs=s[0]
        s=s[1:]
    else:
        lhs=''
    if dSep != '' and s.rfind(dSep) > 0:
        rhs = s[s.rfind(dSep) + 1:]
        s = s[:s.rfind(dSep)]
        if len(s) <= 3: return lhs + s + dSep + rhs
        return lhs + get_split_float(s[:-3], tSep) + tSep + s[-3:] + dSep + rhs
    else:
        if len(s) <= 3: return lhs + s
        return lhs + get_split_float(s[:-3], tSep) + tSep + s[-3:]

def save_to_tempfile(fin):
    """
    @author: SungHyuk Im
    """
    file_name = os.tempnam(get_abs_path(), 'dohn_data_')
    #file_name = os.path.join(get_abs_path() ,file_name)
    fout = open(file_name, 'wb')
    fout.write(fin.read())
    fout.close()
    return file_name

def is_number(arg):
    """
    @author: SungHyuk Im
    @summary: It checks wheter argument is number or not.
    @param arg: Object you want to check
    @requires: True(If number), False(If not number)
    """
    try:
        float(arg)
        return True
    except ValueError:
        return False

def redirect(req, dest, specify = False):
    """
    @author: SungHyuk Im
    """
    if specify:
        mod_python.util.redirect(req, dest)
        return
    dest_url = get_url(req, dest)
    mod_python.util.redirect(req, dest_url)
    return

def replace(htmlfile, content):
    """
    @author: Sangyong Gil
    @summary: It returns HTML source filled up with data generated by Python
    @param htmlfile: html file name
    @param content: generated data to be filled up
    @return: HTML source
    """
    input_template = get_html_with_msg(htmlfile, "")
    result = re.sub("<!---CONTENT!--->", content, input_template) 
    return result

def replace_msg(htmlfile, msg, content):
    """
    @author: Sangyong Gil
    @summary: It returns HTML source filled up with data generated by Python
    @param htmlfile: html file
    @param msg: a message for substitute ex) <!---CONTENT!--->
    @param content: generated data to be filled up
    @return: HTML source
    """
    input_template = get_html_with_msg(htmlfile, "")
    result = re.sub(msg, content, input_template) 
    return result

def check_password(pw):
    """
    @author: Kyeonghwan Jin
    """
    
    """
    Password Policies Should be specified Here
    Should be used in Sign-up View and User-info Edit View
    """
    #less than 4 characters
    if len(pw) < 4:
        return False
    return True
    